﻿using System;
using System.IO;
using System.Windows.Forms;
using log4net.Config;
using ResxCrunch.Properties;
using System.Diagnostics;
using System.Collections.Generic;
using ResxCrunch.Business;
using ResxCrunch.Business.Managers;
using Microsoft.Win32;
using ResxCrunch.Utils;
using System.ComponentModel.Composition;

namespace ResxCrunch.Contracts
{
    /// <summary>
    /// Main app entry
    /// </summary>
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool overrideLicensing = false;

            #region Verify Arguments
            string[] arguments = Environment.GetCommandLineArgs();
            bool startApp = true;

            foreach (string argument in arguments)
            {
                string[] parts = argument.Split('=');

                // Uninstall
                if (parts.Length > 1 && parts[0].Equals("/u", StringComparison.OrdinalIgnoreCase))
                {
                    #region Remove files created by installer
                    //List<string> files = FileMngr.Instance.GetFileList("*.*", "Logs", true);

                    //try
                    //{
                    //    foreach (string file in files)
                    //    {
                    //        File.Delete(file);
                    //    }

                    //    Directory.Delete("Logs");
                    //}
                    //catch (Exception)
                    //{
                    //    // Suppress exceptions
                    //}
                    #endregion Remove files created by installer

                    startApp = false;
                    string path = Environment.GetFolderPath(Environment.SpecialFolder.System);
                    ProcessStartInfo si = new ProcessStartInfo(Path.Combine(path, "msiexec.exe"), string.Concat("/i ", parts[1]));
                    Process.Start(si);

                    Application.Exit();
                }
            }
            #endregion Verify Arguments

            if (startApp)
            {                
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                ConfigureLog();

                bool carryOn = false;

                do
                {
                    carryOn = false;

                    try
                    {
                        // Generate license file
                        //if (SerialMngr.Instance.GenerateLicenseFile(SerialMngr.Instance.GenerateSerial(DateTime.Now, "contact@resxcrunch.com", 1, 0), Settings.Default.DataFilePath))
                        //{
                        //    MessageBox.Show("License file created", Settings.Default.AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //}

                        RegistrationData regData = SerialMngr.Instance.ExtractRegistrationDataFromFile(Settings.Default.DataFilePath, true);

                        if (!overrideLicensing && regData == null)
                        {
                            MessageBox.Show("We are sorry but the application's license info file appears to be corrupt or it cannot be modified. The file can be restored by re-installing the application. If the application was registered please enter the serial again after re-install.", Settings.Default.AppName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            // We have registration info
                            // Verify if only trial
                            if (!overrideLicensing && regData.Email.Equals(Utils.Constants.TrialEmailAddress, StringComparison.InvariantCultureIgnoreCase))
                            {
                                // Trial                                
                                FrmTrialSplash fTrialSplash = new FrmTrialSplash();
                                fTrialSplash.TrialDaysLeft = Math.Max(0, (regData.RegistrationDate.AddDays(Utils.Constants.TrialPeriodDays + 1) - DateTime.Now).Days);

                                switch (fTrialSplash.ShowDialog())
                                {
                                    case DialogResult.OK:
                                        {
                                            carryOn = true;
                                        }
                                        break;

                                    case DialogResult.Retry:
                                        {
                                            Application.Run(new FrmMain());
                                        }
                                        break;
                                }

                            }
                            else
                            {
                                // Registered
                                Application.Run(new FrmMain());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        FrmError formError = new FrmError();
                        formError.Message = ex.ToString();

                        if (formError.ShowDialog() == DialogResult.OK)
                        {
                            carryOn = true;
                        }
                    }
                }
                while (carryOn);
            }
        }

        //private static bool UpdateLicenseFile()
        //{
        //    return SerialMngr.Instance.UpdateDataFile(Settings.Default.DataFilePath);
        //}

        /// <summary>
        /// Configure the log using a config file
        /// </summary>
        private static void ConfigureLog()
        {
            try
            {
                // Log configuration file
                FileInfo fi = new FileInfo("log4net.config");

                // Configure the logger
                XmlConfigurator.Configure(fi);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Logging was not set up successfully. The error message is the following:\n", ex.Message), Settings.Default.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    }
}
